package com.yh.service.impl;

import com.yh.NotFoundException;
import com.yh.dao.TypeReposiory;
import com.yh.po.Type;
import com.yh.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeReposiory typeReposiory;

    @Transactional//添加事务控制
    @Override
    public Type saveType(Type type) {
        return typeReposiory.save(type);
    }

    @Transactional//添加事务控制
    @Override
    public Type getTypeByName(String name) {
        return typeReposiory.findByName(name);
    }

    @Transactional
    @Override
    public Type getType(Long id) {

        Optional<Type> type = typeReposiory.findById(id);

        return type.get();
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeReposiory.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeReposiory.findAll();
    }

    @Override
    public List<Type> listTypeTop() {
//        Sort sort = Sort.by(Sort.Direction.DESC);
//        Pageable pageable = PageRequest.of(0,size,sort);
//        return typeReposiory.findTop(pageable);
        List<Type> all = typeReposiory.findAll();
        Collections.sort(all, new Comparator<Type>() {
            @Override
            public int compare(Type o1, Type o2) {
                int i = o2.getBlogs().size() - o1.getBlogs().size();
                if(i == 0){
                    return o2.getBlogs().size() - o1.getBlogs().size();
                }
                return i;
            }
        });
        return all;
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {

        Optional<Type> t = typeReposiory.findById(id);

        if(t ==null){
            throw new NotFoundException("不存在该类型！");
        }
        BeanUtils.copyProperties(type,t.get());

        return typeReposiory.save(t.get());
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeReposiory.deleteById(id);
    }
}
